// 1. 建立长连接，通道名叫 contentSideBridge 长连接会因为浏览器机制断开，选择其他传输方式
// const port = chrome.runtime.connect({ name: "contentSideBridge" });

// 划词翻译功能实现
let selectionButton: HTMLButtonElement | null = null;
let selectedText = "";

/**
 * 创建翻译按钮
 * @param x - 按钮X坐标
 * @param y - 按钮Y坐标
 */
function createTranslationButton(x: number, y: number) {
	// 如果已存在按钮，先移除
	if (selectionButton) {
		selectionButton.remove();
		selectionButton = null;
	}

	const button = document.createElement("button");
	button.id = "lzp-translation-btn";
	// top: ${y}px;
	// left: ${x}px;
	button.style.cssText = `
        position: fixed;
        top: ${y}px;
        left: ${x}px;
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background-color: #fff;
        border: 1px solid #e0e0e0;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        cursor: pointer;
        z-index: 10000003;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0;
        transition: all 0.2s ease;
    `;

	// 创建图标
	const icon = document.createElement("div");
	// icon.src = chrome.runtime.getURL("icons/icon.png");
	icon.innerHTML = "AI";
	icon.style.cssText = `
		width: 30px;
		height: 30px;
		line-height: 30px;
		background: linear-gradient(45deg, #ff0000, #ff8000, #ffff00, #00ff00, #0080ff, #8000ff);
		-webkit-background-clip: text;
		background-clip: text;
		-webkit-text-fill-color: transparent;
		font-weight: bold;
		font-size: 16px;
		`;
	button.appendChild(icon);

	// 添加悬停效果
	button.addEventListener("mouseenter", () => {
		button.style.transform = "scale(1.1)";
		button.style.boxShadow = "0 4px 12px rgba(0, 0, 0, 0.2)";
	});

	button.addEventListener("mouseleave", () => {
		button.style.transform = "scale(1)";
		button.style.boxShadow = "0 2px 8px rgba(0, 0, 0, 0.15)";
	});

	// 点击事件：打开侧边栏并传递选中文本
	button.addEventListener("click", async () => {
		button.remove();
		selectionButton = null;

		// 打开侧边栏
		await chrome.runtime.sendMessage({
			action: "content",
			data: selectedText,
		});
		// port.postMessage({ source: "content", payload: selectedText });
	});

	document.body.appendChild(button);
	selectionButton = button;
}

/**
 * 获取选中的文本
 */
function getSelectedText(): string {
	const selection = window.getSelection();
	return selection ? selection.toString().trim() : "";
}

/**
 * 处理鼠标抬起事件
 */
function handleMouseUp(event: MouseEvent) {
	const target = event.target as HTMLElement;
	if (selectionButton && selectionButton.contains(target)) return;
	const text = getSelectedText();
	if (text && text.length > 0) {
		selectedText = text;

		// 延迟显示按钮，避免干扰正常选择
		setTimeout(() => {
			// 获取选中位置计算按钮坐标存在问题
			const selection = window.getSelection();
			if (selection && selection.rangeCount > 0) {
				// const range = selection.getRangeAt(0);
				// const rect = range.getBoundingClientRect();
				// // 计算按钮位置（选择文本的右下角）
				// const x = rect.right + window.scrollX;
				// const y = rect.bottom + window.scrollY;
				// createTranslationButton(x, y);
				createTranslationButton(event.clientX + 10, event.clientY + 10);
			}
		}, 100);
	} else {
		// 如果没有选中文本，隐藏按钮
		if (selectionButton) {
			selectionButton.remove();
			selectionButton = null;
		}
	}
}

/**
 * 处理文档点击事件（点击其他地方时隐藏按钮）
 */
function handleDocumentClick(event: MouseEvent) {
	const target = event.target as HTMLElement;
	if (selectionButton && !selectionButton.contains(target)) {
		selectionButton.remove();
		selectionButton = null;
	}
}

/**
 *  处理选择变化事件
 */
function selectionchange() {
	const text = getSelectedText();
	if (!text) {
		// 如果取消选择，隐藏按钮
		if (selectionButton) {
			selectionButton.remove();
			selectionButton = null;
		}
	}
}

/**
 * 初始化划词翻译功能
 */
function initTranslationFeature() {
	// 监听鼠标抬起事件
	document.addEventListener("mouseup", handleMouseUp);

	// 监听文档点击事件
	document.addEventListener("click", handleDocumentClick);

	// 监听选择变化事件
	document.addEventListener("selectionchange", selectionchange);
}

// function removeListener() {
// 	document.removeEventListener("mouseup", handleMouseUp);
// 	document.removeEventListener("click", handleDocumentClick);
// 	document.removeEventListener("selectionchange", selectionchange);
// }
// // 3. 防止僵尸端口
// port.onDisconnect.addListener(() => {
// 	removeListener();
// });

// 页面加载完成后初始化
if (document.readyState === "loading") {
	document.addEventListener("DOMContentLoaded", initTranslationFeature);
} else {
	initTranslationFeature();
}
